/*
    Copyright 2009 Barnet Wagman

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

        http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
 */

package ot;

import java.io.*;

/**
 *
 * @author Barnet Wagman
 */

public class SerializerTable implements Serializable {
    static final long serialVersionUID = ConstantsOt.UID_VERSION;

    Serializer[] srzs;
    Serializer defaultSerializer;

    public SerializerTable(Serializer defaultSerializer) {
        this.defaultSerializer = defaultSerializer;
        srzs = new Serializer[] { new GzipSerializer(),
                                  new StandardSerializer() };
        addSerializer(defaultSerializer);
    }

        /** Gets the {@link Serializer} that has object name extension
         *  <tt>name</tt>.
         * @param name
         * @return the {@link Serializer} object name extension param <tt>name</tt>
         *      or null there is not matching serializer.  If <tt>name</tt> is <tt>null</tt>
         *      the default serializer is returned.
         */
    public Serializer getSerializer(String name) {
        if ( name == null ) return(defaultSerializer);
        for ( Serializer s : srzs ) {
            if ( name.toLowerCase().endsWith("." + s.getObjectNameExtension()) ) {
                return(s);
            }
        }
        return(defaultSerializer);
    }

    public Serializer getSer(String name) {
        return(getSerializer(name));
    }

    public Serializer getSer(Path path) {
        return(getSerializer(path.toPathString()));
    }

    public Serializer getSer(LocO loc) {
        return(getSerializer(loc.getPath().toPathString()));
    }

    public Serializer getDefaultSerializer() {
        return(defaultSerializer);
    }

    public void addSerializer(Serializer s) {
        if ( hasSerializer(s) ) return;

        Serializer[] tmp = new Serializer[srzs.length + 1];
        System.arraycopy(srzs,0,tmp,0,srzs.length);
        tmp[tmp.length-1] = s;
        srzs = tmp;
    }

    boolean hasSerializer(Serializer s) {
        String target = s.getClass().getName();
        for ( Serializer x : srzs ) {
            if ( target.equals(x.getClass().getName()) ) return(true);
        }
        return(false);
    }
}
